package com.xhdd.conf;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

@Component
public class EsConf {
    @Value("${es8.host}")
    String host;
    @Value("${es8.port}")
    Integer port;
    @Value("${es8.http}")
    String http;

    @Bean
    private ElasticsearchClient getElasticsearchClient() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
//        Path caCertificatePath = Paths.get("D:\\elasticsearch-8.13.2\\config\\certs\\http_ca.crt");
//        // 创建证书工厂
//        CertificateFactory factory = CertificateFactory.getInstance("X.509");
//        Certificate trustedCa = factory.generateCertificate(Files.newInputStream(caCertificatePath));
//        // 创建密钥库
//        KeyStore trustStore = KeyStore.getInstance("pkcs12");
//        trustStore.load(null, null);
//        trustStore.setCertificateEntry("ca", trustedCa);
//        // 创建SSL上下文构建器
//        SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
//        SSLContext sslContext = sslContextBuilder.build();
//
//        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//        credentialsProvider.setCredentials(AuthScope.ANY,
//                new UsernamePasswordCredentials("elastic", "_p-KpEKzoXWL7hIj-lrn"));
//        RestClient restClient = RestClient.builder(
//                        new HttpHost("localhost", 9200, "https"))
//                .setHttpClientConfigCallback(httpClientBuilder ->
//                        httpClientBuilder.setSSLContext(sslContext)
//                                .setDefaultCredentialsProvider(credentialsProvider))
//                .build();
        /*关闭认证*/
        HttpHost httpHost = new HttpHost(host, port, http);
        RestClient restClient = RestClient.builder(httpHost).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient esClient = new ElasticsearchClient(transport);
        return esClient;
    }


}